package com.ecp.commons.task;

import java.util.Arrays;

import org.jcrontab.log.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ecp.commons.cache.CacheService;
import com.ecp.commons.msg.ClusterMSGServer;

@Repository("cacheMSGTask")
public class CacheMSGTask implements Task {

	public static final String	MSG_TYPE_CACHE		= "cache";

	public static final String	CACHE_TYPE_SEND		= "send";
	public static final String	CACHE_TYPE_RECEIVE	= "receive";

	private String[]			cacheMsg			= new String[3];

	@Autowired
	private CacheService		entityCache;

	/**
	 * params[0] must be msg type. [cache]<br>
	 * params[1] must be cache type. [send/receive]<br>
	 * params[2] must be operate type. [delete/add]<br>
	 * params[3] is msg body.
	 * params[4] is msg body.
	 */
	@Override
	public void setParams(Object params) {

		String[] paramAry = (String[]) params;
		if (!paramAry[0].equals(MSG_TYPE_CACHE)) {
			return;
		}
		this.cacheMsg = paramAry;

		TaskServer.getInstance().append(this);
	}

	@Override
	public void execute() throws Exception {
		if (!cacheMsg[0].equals(MSG_TYPE_CACHE)) {
			throw new Exception("Wrong cache data.");
		}

		if (cacheMsg[1].equals(CACHE_TYPE_SEND)) {
			ClusterMSGServer.sendData(Arrays.toString(cacheMsg));
		} else {//MSG_TYPE_RECEIVE
			if (cacheMsg.length != 5) {
				Log.info("invalid message: " + Arrays.toString(cacheMsg));
			} else if (cacheMsg[2].equals("remove")) {
				entityCache.afterRemoveEntity(cacheMsg[3], cacheMsg[4], false);
			} else if (cacheMsg[2].equals("add")) {
				entityCache.afterAddEntity(cacheMsg[3], cacheMsg[4], false);
			} else if (cacheMsg[2].equals("update")) {
				entityCache.afterUpdateEntity(cacheMsg[3], cacheMsg[4], false);
			}
		}
	}

}
